# RSA.py
# RSA加密算法
# -*- coding: utf-8 -*-
"""
Created on 2021

@author: Ximing
"""

import random

# 生成随机文件
print('正在生成随机文件')
f = open('scautext.txt', 'w+')
for i in range(100):
    for j in range(random.randint(10, 20)):
        f.write(chr(random.randint(0, 25) + ord('a')))
    f.write("\n")


# 找出与（p-1）*(q-1)互质的数e
def co_prime(s):
    while True:
        e = random.choice(range(100))
        if e<3:
            continue
        x = gcd(e, s)
        if x == 1:  # 如果最大公约数为1，则退出循环返回e
            break
    return e


# 求两个数的最大公约数
def gcd(a, b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)


# 根据e*d mod s = 1,找出d
def find_d(e, s):
    for d in range(100000000):  # 随机太难找，就按顺序找到d,range里的数字随意
        x = (e * d) % s
        if x == 1:
            return d


# RSA.py
class RSA():
    def __init__(self):
        self.Pk, self.Sk = self.creatKey()

    # 生成公钥和私钥
    def creatKey(self):
        Pk = []
        Sk = []
        print("RSA加解密部分：")
        p = int(input("请输入质数p:"))
        q = int(input("请输入质数q:"))
        n = p * q
        s = (p - 1) * (q - 1)
        e = co_prime(s)
        Pk.append(n)
        Sk.append(n)
        print("根据e和(p-1)*(q-1))互质得到: e=", e)
        d = find_d(e, s)
        print("根据(e*d)mod((p-1)*(q-1))=1 得到 d=", d)
        print("公钥: n=", n, "e=", e)
        print("私钥: n=", n, "d=", d)
        Pk.append(e)
        Sk.append(d)
        return Pk, Sk

    def encrypt(self, data):
        return chr((data ** self.Pk[1]) % self.Pk[0])

    def decrypt(self, data):
        return chr((data ** self.Sk[1]) % self.Sk[0])


rsa = RSA()
print('开始加密')
with open('scautext.txt', 'r', encoding='utf-8') as f:
    with open('encode.txt', 'w+', encoding='utf-8') as f1:
        while True:
            data = f.read(1)
            if data != '':
                data = rsa.encrypt(ord(data))
                f1.write(data)
            else:
                break
        f1.close()
    f.close()
print('加密完成前往encode.txt查看结果')

print('开始解密')
with open('encode.txt', 'r', encoding='utf-8') as f:
    with open('decode.txt', 'w+', encoding='utf-8') as f1:
        while True:
            data = f.read(1)
            if data != '':
                data = rsa.decrypt(ord(data))
                f1.write(data)
            else:
                break
print('解密完成前往decode.txt查看结果')
